package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.InsertionNotAllowedException;
import com.sky.exception.UpdateNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.RedisUtil;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

	@Autowired
	private DishMapper dishMapper;
	@Autowired
	private DishFlavorMapper dishFlavorMapper;
	@Autowired
	private SetmealDishMapper setmealDishMapper;
	@Autowired
	private SetmealMapper setmealMapper;
	@Autowired
	private RedisUtil redisUtil;


	/**
	 * 新增菜品和对应口味
	 */
	@Override
	@Transactional
	public void saveWithFlavor(DishDTO dishDTO) {

		//如果存在菜品名称则触发业务异常
		if (dishMapper.getByName(dishDTO.getName()) != null) {
			throw new InsertionNotAllowedException(MessageConstant.DISH_ALREADY_EXISTS);
		}

		//菜品对象属性拷贝
		Dish dish = new Dish();
		BeanUtils.copyProperties(dishDTO, dish);
		dish.setStatus(StatusConstant.DISABLE);
		//向菜品表插入一条数据
		dishMapper.insert(dish);
		//插入菜品对象后获取insert语句生成的菜品主键值，作为口味记录的外键
		Long dishId = dish.getId();

		//获取菜品的口味集合对象
		List<DishFlavor> flavors = dishDTO.getFlavors();
		//向口味表插入多条数据
		if (flavors != null && flavors.size()>0) {
			flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
			dishFlavorMapper.insertBatch(flavors);
		}
	}

	/**
	 * 菜品分页查询
	 *
	 * @param dishPageQueryDTO
	 * @return
	 */
	@Override
	public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
		// 开始分页查询，下一条sql执行时进行分页，自动加入limit关键字分页
		PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

		Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

		return new PageResult(page.getTotal(), page.getResult());

	}

	/**
	 * 批量删除菜品
	 *
	 * @param ids
	 */
	@Override
	@Transactional
	public void delete(List<Long> ids) {

		//判断菜品是否是起售状态，是则无法无法删除
		ids.forEach(id ->{
			if (StatusConstant.ENABLE.equals(dishMapper.getById(id).getStatus())) {
				throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
			}
		});
		//判断菜品是否关联了套餐，是则无法删除
		List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
		if (setmealIds != null && setmealIds.size()>0) {
			throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
		}

		//删除菜品表和口味表中菜品id对应的记录
		ids.forEach(id ->{
			//删除菜品表中的菜品数据
			dishMapper.deleteById(id);
			//删除口味表中和菜品关联的口味
			dishFlavorMapper.deleteByDishId(id);
		});
	}

	/**
	 * 根据id查询菜品和对应口味信息
	 *
	 * @param id
	 * @return
	 */
	@Override
	public DishVO getByIdWithFlavor(Long id) {
		//根据菜品id查询菜品数据
		Dish dish = dishMapper.getById(id);
		//根据菜品id查询口味数据
		List<DishFlavor> flavorList = dishFlavorMapper.getByDishId(id);
		//将查询到的口味数据封装到VO
		DishVO dishVO = new DishVO();
		BeanUtils.copyProperties(dish, dishVO);
		dishVO.setFlavors(flavorList);

		return dishVO;
	}

	/**
	 * 根据id修改菜品基本信息和对应的口味信息
	 *
	 * @param dishDTO
	 */
	@Override
	@Transactional
	public void updateWithFlavor(DishDTO dishDTO) {
		//如果修改了菜品名
		if (!dishMapper.getById(dishDTO.getId()).getName().equals(dishDTO.getName())){
			//并且修改后的菜品名称已经存在则触发业务异常
			if (dishMapper.getByName(dishDTO.getName()) != null) {
				throw new UpdateNotAllowedException(MessageConstant.DISH_ALREADY_EXISTS);
			}
		}

		//菜品对象属性拷贝
		Dish dish = new Dish();
		BeanUtils.copyProperties(dishDTO, dish);
		//修改菜品表信息
		dishMapper.update(dish);

		//修改口味表信息
		//删除口味表中原菜品id对应口味记录
		dishFlavorMapper.deleteByDishId(dish.getId());
		//重新向口味表插入多条数据
		List<DishFlavor> flavors = dishDTO.getFlavors();
		if (flavors != null && flavors.size()>0) {
			flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
			dishFlavorMapper.insertBatch(flavors);
		}

		//并且在缓存中删除该菜品对应的分类
		String key = "dish_"+dish.getCategoryId();
		redisUtil.delete(key);

	}

	/**
	 * 启售停售指定id的菜品
	 *
	 * @param status
	 * @param id
	 */
	@Override
	@Transactional
	public void startOrStop(Integer status, Long id) {

		Dish dish = Dish.builder().id(id).status(status).build();
		dishMapper.update(dish);

		//如果是停售，则包含该菜品的套餐也应停售
		if (StatusConstant.DISABLE.equals(status)) {
			//查询包含该菜品id的套餐集合
			List<Long> dishId = new ArrayList<>();
			dishId.add(id);
			List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishId);
			//如果有值则逐个停售
			if (setmealIds != null && setmealIds.size() > 0) {
				for (Long setmealId : setmealIds) {
					Setmeal setmeal = Setmeal.builder()
							.id(setmealId)
							.status(StatusConstant.DISABLE)
							.build();
					setmealMapper.update(setmeal);
				}
			}
		}

		//并且在缓存中删除该菜品对应的分类
		String key = "dish_"+dishMapper.getById(id).getCategoryId();
		redisUtil.delete(key);
	}

	/**
	 * 根据分类id查询该分类下的所有起售菜品
	 *
	 * @param categoryId
	 */
	@Override
	public List<Dish> list(Long categoryId) {
		Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
		return dishMapper.list(dish);
	}

	/**
	 * 根据菜品分类id和起售禁售状态查询菜品及其菜品的口味
	 *
	 * @param dish
	 * @return
	 */
	@Override
	public List<DishVO> listWithFlavor(Dish dish) {
		// 构造redis中的key，规则：dish_分类id
		String key = "dish_"+dish.getCategoryId();
		//查询redis中是否存在菜品数据
		//如果有就直接返回
		 List<DishVO> lsit = (List<DishVO>) redisUtil.get(key);
		if (lsit!=null){
			return lsit;
		}

		List<Dish> dishList = dishMapper.list(dish);
		List<DishVO> dishVOList = new ArrayList<>();
		dishList.forEach( d ->{
			DishVO dishVO = new DishVO();
			BeanUtils.copyProperties(d,dishVO);
			//根据菜品id查询对应口味
			List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(d.getId());
			dishVO.setFlavors(dishFlavors);
			dishVOList.add(dishVO);
		});

		// 缓存中没有则查询数据库后放入数据库
		redisUtil.set(key,dishVOList);
		return dishVOList;
	}
}
